package com.example.gateway.filter;

import com.example.gateway.feign.UserFeign;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author kangshuai
 */
@Slf4j
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Resource
    private UserFeign userFeign;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下⽂中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String path = request.getPath().toString();
        if (path.startsWith("/api/user") || path.startsWith("/api/code")) {
            // 合法请求，放⾏，执⾏后续的过滤器
            return chain.filter(exchange);
        } else {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            String token = "";
            if (cookies.containsKey("token")) {
                token = cookies.getFirst("token").getValue();
                if (token != null && !token.isEmpty()) {
                    //远程验证
                    String email = userFeign.info(token).getData();
                    if (email != null && !email.equals("")) {
                        // 合法请求，放⾏，执⾏后续的过滤器
                        return chain.filter(exchange);
                    }
                }
            }
            // 拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

